package com.zmx.common.common.utils;

import com.zmx.common.common.config.ApplicationContextRegister;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: HttpClient连接池，有效提高http访问速度，提升性能
 * @ClassName: PoolHttpClientUtil
 * @Author zhaomxr
 * @Date 2021-11-30 15:41
 */
public class PoolHttpClientUtil {

    private static CloseableHttpClient httpClient = null;

    static {
        httpClient = (CloseableHttpClient) ApplicationContextRegister.getApplicationContext().getBean("httpClient");
    }

    /**
     * httpGet 请求
     * @param data
     * @param url
     * @return
     */
    public static String httpGet (String url, Map<String, String> data) {
        if (url.endsWith("/")) {
            url.substring(url.length() - 2, url.length() - 1);
        }

        if(!CollectionUtils.isEmpty(data)){
            //请求参数
            StringBuilder params = new StringBuilder(url);
            params.append("?");
            data.forEach((key, value) -> {
                params.append(key);
                params.append("=");
                params.append(value);
                params.append("&");
            });
            url = params.toString().substring(params.length() - 2, params.length() - 1);
        }

        HttpGet httpGet = new HttpGet(url);
        return execute(httpGet);
    }

    /**
     * httpPost 请求, 基于实体bean发送参数
     * @param data
     * @param url
     * @return
     */
    public static String httpPost(String url, Object object) {
        HttpPost httpPost = new HttpPost(url);
        Map<String, String> data = null;

        try {
            if (object instanceof Map && object != null) {
                data = (Map) object;
            } else {
                data = JacksonUtil.jsonStringToMap(JacksonUtil.toJsonString(object));
            }

            if (!CollectionUtils.isEmpty(data)) {
                //拼接参数
                List<NameValuePair> params = new ArrayList<NameValuePair>(data.size());
                data.forEach((key, value) -> {
                    params.add(new BasicNameValuePair(key, value));
                });
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return execute(httpPost);
    }

    /**
     * httpPost 请求
     * @param data
     * @param url
     * @return
     */
    public static String httpPost(String url, Map<String, String> data) {
        HttpPost httpPost = new HttpPost(url);
        //拼接参数
        List<NameValuePair> params = new ArrayList<NameValuePair>(data.size());
        data.forEach((key, value) -> {
            params.add(new BasicNameValuePair(key, value));
        });

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return execute(httpPost);
    }

    /**
     * 执行post，get请求
     * @param request
     * @return
     */
    private static String execute(HttpUriRequest request) {
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                return EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(response);
        }
        return "";
    }

    private static void close(CloseableHttpResponse response) {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
